package org.wekit.engine.pvm.process;

import java.util.ArrayList;
import java.util.List;

import org.wekit.engine.pvm.PvmProcessDefinition;
import org.wekit.engine.pvm.PvmProcessInstance;
import org.wekit.engine.pvm.runtime.ExecutionImpl;
import org.wekit.engine.pvm.runtime.InterpretableExecution;

/**
 * 流程定义实现类
 * @author HuangWeili
 *
 */
public class ProcessDefinition extends Scope implements PvmProcessDefinition{

	private static final long serialVersionUID = -4305759872153539866L;
    //流程名称
	protected String name;
	//流程定义描述
	protected String description;
	//默认初始节点
	protected Activity initial;
	//初始堆栈，流程定义的父子关系，用于子流程
	protected List<Activity> initialActivityStack=new ArrayList<Activity>();
	/**
	 * 构造
	 * @param id
	 */
	public ProcessDefinition(String id) {
		super(id,null);
		this.processDefinition=this;
	}

	@Override
	public String getName() {
		return this.name;
	}

	//获取描述信息
	@Override
	public String getDescription() {
		return this.description!=null?this.description:getProperty("documentation").toString();
	}

	/**
	 * 设置初始节点
	 * @param initial
	 */
	public void setInitial(Activity initial)
	{
		this.initial=initial;
	}
	
	@Override
	public Activity getInitial() {
		return this.initial;
	}

	@Override
	public String getDeploymentId() {
		return this.id;
	}
	
	//设置名称
	public void setName(String name)
	{
		this.name=name;
	}
	

	@Override
	public PvmProcessInstance createProcessInstance() {
		InterpretableExecution processInstance=this.newProcessInstance();
		processInstance.setProcessDefinition(this);
		processInstance.setProcessInstance(processInstance);
		
		//初始实例
		processInstance.initialize();
		
		InterpretableExecution scopeInstance=processInstance;
		
		List<Activity> initialActivities=getInitialActivityStack();
		for(Activity initialActivity:initialActivities)
		{
			if(initialActivity.isScope())
			{
				scopeInstance=(InterpretableExecution)scopeInstance.createExecution();
				scopeInstance.setActivity(initialActivity);
				if(initialActivity.isScope())
				{
					scopeInstance.initialize();
				}
				
			}
			
		}
		
		return processInstance;
	}
	
	protected InterpretableExecution newProcessInstance()
	{
		return new ExecutionImpl();
	}

	public void setDescription(String description)
	{
	 this.description=description;
	}

	//获取初始列表压榨
	public synchronized List<Activity> getInitialActivityStack(){
		Activity activity=initial;
		while(activity!=null)
		{
			initialActivityStack.add(0,activity);
			activity=activity.getParentActivity();
		}
	    return initialActivityStack;
	}	
}
